﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Musicman.Common.Entities;
using Musicman.Business;
using Musicman.Common.Utilities;
using System.Net.Mail;
using System.IO;
using Musicman.Utilities;
using Musicman.Common;

namespace Musicman.Client2
{
    public partial class MessagesForm : Form
    {
        DateTime firstMessage = DateTime.MinValue;
        DateTime lastMessage = DateTime.MinValue;
        public long UserID { get; set; }

        Dictionary<long, UserMessage> dictMessages = new Dictionary<long, UserMessage>();


        public MessagesForm()
        {
            InitializeComponent();
            KeyPreview = true;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape)
            {
                this.Hide();
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void MessagesForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
            }
        }

        public void RefreshData()
        {
            firstMessage = DateTime.MinValue;
            lastMessage = DateTime.MinValue;
            RefreshData(true);
        }

        public void RefreshData(bool next)
        {
            List<UserMessage> messages = UserMassageManager.Instance.LoadUserMessages(12,
                next ? lastMessage : firstMessage, next);

            if (messages.Count != 0)
            {
                firstMessage = messages[0].MessageDate;
                lastMessage = messages[messages.Count - 1].MessageDate;

                dictMessages.Clear();
                treeViewMessages.Nodes.Clear();
                foreach (UserMessage message in messages)
                {
                    dictMessages.Add(message.MessageID, message);
                    string msgBody = String.Format("{0}{1}",
                        message.MessageDate.ToString("[dd-MM-yyyy hh:mm]"),
                        message.Commments == null ? "" : String.Format(" ({0})", message.Commments.Count));
                    TreeNode parentNode = treeViewMessages.Nodes.Add(message.MessageID.ToString(), msgBody);
                    parentNode.ToolTipText = message.Message;
                    if (message.Commments != null)
                    {
                        foreach (UserMessage comment in message.Commments)
                        {
                            dictMessages.Add(comment.MessageID, comment);
                            msgBody = comment.MessageDate.ToString("[dd-MM-yyyy hh:mm]");
                            TreeNode childNode = parentNode.Nodes.Add(comment.MessageID.ToString(), msgBody);
                            childNode.ToolTipText = comment.Message;
                        }
                    }
                }
            }
        }

        private void SendNotificationMail(long messageID)
        {
            UserMessage message = UserMassageManager.Instance.GetFullMessage(messageID);
            if (message != null)
            {
                long meID = UserID;
                MailAddress ema = null;
                MailMessage email = new MailMessage();

                email.From = new MailAddress("musicmanservices@musicman.com", "Musicman");
                User u = null;
                for (int i = 0; i < message.Commments.Count; i++)
                {
                    u = message.Commments[i].Sender;
                    ema = new MailAddress(u.Emailaddress);
                    if (u.Personid != meID && !email.To.Contains(ema))
                    {
                        email.To.Add(ema);
                    }
                }

                UserMessage comment = message.Commments[message.Commments.Count - 1];
                User comentator = comment.Sender;
                u = message.Sender;
                ema = new MailAddress(u.Emailaddress);
                if (u.Personid != meID && !email.To.Contains(ema))
                {
                    email.To.Add(ema);
                }
                string mailTemplate = "";
                String folder = AppDomain.CurrentDomain.BaseDirectory;
                using (StreamReader sr = new StreamReader(File.Open(Path.Combine(folder, @"Resources\post_commented.html"), FileMode.Open, FileAccess.Read)))
                {
                    mailTemplate = sr.ReadToEnd();
                }
                email.Subject = String.Format("{0} {1}'s post commented", u.Firstname, u.Lastname);
                email.Body = String.Format(mailTemplate,
                    comentator.Firstname,
                    comentator.Lastname,
                    u.Firstname,
                    u.Lastname,
                    message.Message,
                    comment.Message);
                email.IsBodyHtml = true;
                MailSender.Instance.SendMailAsync(email);
            }

        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            RefreshData(false);
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            RefreshData(true);
        }

        private void treeViewMessages_AfterSelect(object sender, TreeViewEventArgs e)
        {
            long messageId = 0;
            if (Int64.TryParse(e.Node.Name, out messageId))
            {
                UserMessage msg = dictMessages[messageId];
                lblFromValue.Text = msg.Sender.Firstname;
                lblDateValue.Text = msg.MessageDate.ToString("[dd-MM-yyyy hh:mm]");
                txtMessage.Text = msg.Message;
            }
        }

        private void treeViewMessages_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible == false)
            {
                UserManager.Instance.UpdateLastWallVisit(this.UserID);
            }
        }

        private void messageSend_Click(object sender, EventArgs e)
        {
            bool newMessage = (sender as Button) == btnNewMessage;
            long messageId = 0;
            if (treeViewMessages.SelectedNode != null)
            {
                if (treeViewMessages.SelectedNode.Parent == null)
                {
                    Int64.TryParse(treeViewMessages.SelectedNode.Name, out messageId);
                }
                else
                {
                    Int64.TryParse(treeViewMessages.SelectedNode.Parent.Name, out messageId);
                }
            }
            UserMessage msg = new UserMessage();
            msg.MessageDate = DateTime.Now;
            User user = new User();
            user.Personid = this.UserID;
            msg.Sender = user;
            msg.Message = txtNewMessage.Text;
            if (!newMessage)
            {
                if (messageId != 0)
                {
                    msg.Parent = dictMessages[messageId];
                }
            }
            if (UserMassageManager.Instance.InsertMessage(msg))
            {
                // refresh current view
                RefreshData();
                txtNewMessage.Text = "";
            }
            if (!newMessage)
            {
                if (messageId != 0 && Boolean.Parse(AppSettingsHelper.GetWebConfigValue(Constants.EmailEnabled)))
                {
                    SendNotificationMail(messageId);
                }
            }
        }
    }
}
